<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>视频会话</title>
    <link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.3.0/weui.min.css"/>
    <link rel="stylesheet" href="css/index.css"/>
    <link rel="stylesheet" href="css/style.css"/>
</head>
<body>
    <textarea id="tvArea" class="left-float-window" readonly></textarea>
    <div class="right-float-window">
        <video id="remoteView" class="main-video" autoplay=""></video>
    </div>
    <div class="app-location"
         style="border-radius: 10px;
                margin-top: 50px">

        <div class="main-video-parent">
            <video id="localView" class="main-video" autoplay=""></video>
        </div>

        <div class="weui-form__control-area">
            <div class="weui-cells__group weui-cells__group_form">
                <div class="weui-cells weui-cells_form">
                    <div class="weui-cell weui-cell_active">
                        <div class="weui-cell__hd"><label class="weui-label">用户号码</label></div>
                        <div class="weui-cell__bd">
                            <input id="nickName" class="weui-input" placeholder="请填写用户号码"/>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="weui-flex">
            <div class="weui-flex__item">
                <a id="close" href="javascript:" class="weui-btn weui-btn_warn">取消</a>
            </div>
            <div class="weui-flex__item">
                <a id="submit" href="javascript:" class="weui-btn weui-btn_primary">呼叫</a>
            </div>
        </div>

    </div>


    <div class="js_dialog" id="androidDialog2" style="display: none;">
        <div class="weui-mask"></div>
        <div class="weui-dialog weui-skin_android">
            <div id="dialog_text" class="weui-dialog__bd">
                提示信息
            </div>
            <div class="weui-dialog__ft">
                <a id="btnClose" href="javascript:" class="weui-dialog__btn weui-dialog__btn_default">辅助操作</a>
                <a id="btnSure" href="javascript:" class="weui-dialog__btn weui-dialog__btn_primary">主操作</a>
            </div>
        </div>
    </div>
    <div id="loadingToast" style="display: none;">
        <div class="weui-mask_transparent"></div>
        <div class="weui-toast">
            <i class="weui-loading weui-icon_toast"></i>
            <!--<p id="toast_text" class="weui-toast__content">数据加载中</p>-->
        </div>
    </div>

    <script language=javascript src='https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js'></script>
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script src="https://res.wx.qq.com/open/libs/weuijs/1.2.1/weui.min.js"></script>
    <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>-->
    <script src='js/socket.io.js'></script>
    <script language=javascript src='js/http.js'></script>
    <script language=javascript src='js/md5.js'></script>
    <script language=javascript src='js/RTC.js'></script>
    <script language=javascript src='js/socketConnect.js'></script>
    <script type="text/javascript">
        const localVideo=document.getElementById('localView');
        const remoteVideo=document.getElementById('remoteView');
        const tvarea=$('#tvArea');
        const nickName=$('#nickName');

        let localStream=null;
        let user={};
        user['id']='123410';
        user['name']='蒋大师';
        user['sex']=0;
        let room_name;
        /**
         * 音视频配置
         * @type {{video: boolean, audio: boolean}}
         */
        const config={
            video: true,
            audio: true
        };
        function alart(msg,submit,callBack) {
            $('#dialog_text').html(msg);
            $('#btnSure').html(submit);
            $('#btnClose').hide();
            $('#btnSure').off('click').on('click',function () {
                $('#androidDialog2').fadeOut(200);
                callBack();
            });
            $('#androidDialog2').fadeIn(200);
        }

        function alartClose(msg,close,closeBack,submit,callBack) {
            $('#dialog_text').html(msg);
            $('#btnSure').html(submit);
            $('#btnClose').show()
            $('#btnClose').html(close);
            $('#btnClose').off('click').on('click',function (event) {
                $('#androidDialog2').fadeOut(200);
                closeBack();
            });
            $('#btnSure').off('click').on('click',function (event) {
                $('#androidDialog2').fadeOut(200);
                callBack();
            });
            $('#androidDialog2').fadeIn(200);
        }

        function loading(){
            if ($('#loadingToast').css('display') != 'none') return;
            $('#loadingToast').fadeIn(100);
        }

        function dismiss() {
            if ($('#loadingToast').css('display') == 'none') return;
            $('#loadingToast').fadeOut(100);
        }


        //访问用户媒体设备的兼容方法
        function getUserMedia(constraints, success, error) {
            if (navigator.mediaDevices.getUserMedia) {
                //最新的标准API
                navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
            } else if (navigator.webkitGetUserMedia) {
                //webkit核心浏览器
                navigator.webkitGetUserMedia(constraints,success, error)
            } else if (navigator.mozGetUserMedia) {
                //firfox浏览器
                navigator.mozGetUserMedia(constraints, success, error);
            } else if (navigator.getUserMedia) {
                //旧版API
                navigator.getUserMedia(constraints, success, error);
            }
        }

        function success(stream) {
            localStream=stream;
            //兼容webkit核心浏览器
            console.log("本地",stream);
            localVideo.srcObject = stream;
            // remoteVideo.srcObject = stream;
        }

        function error(err){
            console.log(err);
        }

        function getStream(){
            if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
                //调用用户媒体设备, 访问摄像头
                getUserMedia(config, success, error);
            } else {
                alert('不支持访问用户媒体');
            }
        }

        function open(){
            socket.connect('http://funnymudpee.qicp.vip',user,function (contacts) {
                let msg=tvarea.val();
                for(let key in contacts){
                    msg=msg+key+"在线。\n";
                }
                console.log(msg);
                tvarea.val(msg);
            },function message(data) {
                let fromid=data['from'];
                let sdp=data['sdp'];
                let candidate=data['candidate'];
                if(data['type']=='offer'){
                    rtc.responseOffer(localStream,fromid,sdp);
                    rtc.createAnswer(fromid,function asn(answer) {
                        socket.sendSDP(answer,user['id'],fromid);
                    },function iceBack(ice) {
                        socket.sendIceData(ice,user['id'],fromid);
                    },function trackBack(event) {
                        console.log("网络流",event.stream);
                        remoteVideo.srcObject=event.stream;
                    });
                }else if(data['type']=='answer'){
                    rtc.responseAnswer(fromid,sdp);
                }else if(data['type']=='candidate'){
                    rtc.responseIceDate(fromid,data['id'],data['label'],candidate);
                }
            },function beSingleCall(data) {
                let fromUser=data['from'];
                room_name=data['room'];
                alartClose("用户"+fromUser['name']+"请求与你通话，是否接受？","挂断",function () {
                    socket.refuseCall(room_name,user['id'],fromUser['id']);
                },"接听",function () {
                    socket.intoRoom(room_name,user['id']);
                });
            },function getRoom(data) {
                room_name = data;
                console.log("申请房间2",new Date().getTime());
                socket.intoRoom(room_name,user['id']);
            },function create() {
                socket.singleCall(room_name,user['id'],nickName.val(),function beRefuse(refuseData) {
                    let msg=tvarea.val();
                    msg=msg+"用户"+refuseData['from']+"拒绝了你的邀请\n";
                    tvarea.val(msg);
                    socket.outRoom(room_name,user['id']);
                    dismiss();
                    alart("用户"+refuseData['from']+"拒绝了你的邀请","确定",function () {

                    });
                });
            },function join(joindata) {
                dismiss();
                rtc.createOffer(localStream,joindata,function offerCreate(offer) {
                    console.log(offer);
                    socket.sendSDP(offer,user['id'],joindata);
                },function iceCall(ice) {
                    socket.sendIceData(ice,user['id'],joindata);
                },function trackBack(event) {
                    console.log("网络流2",event.stream);
                    remoteVideo.srcObject=event.stream;
                });
            },function someBodyOut(data) {
                rtc.close(data)
                remoteVideo.pause();
                let msg=tvarea.val();
                msg=msg+"用户"+data+"结束了通话\n";
                tvarea.val(msg);

                socket.outRoom(room_name,user['id']);

                alart("用户"+data+"结束了通话","确定",function () {

                });

            });
        }

        $(function () {
            getStream();
            open();

            $('#submit').unbind('click').click(function () {
                console.log("申请房间",new Date().getTime());
                loading();
                socket.getRoom(user['id']);
            });

            $('#close').unbind('click').bind('click',function () {
                socket.outRoom(room_name,user['id']);
                remoteVideo.pause();
                rtc.close();
            });

        });
        window.onbeforeunload=function () {
            socket.close();
        };
    </script>
</body>
</html>